<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use App\Models\Product\MainProduct;
use App\Models\Product\ProductTranslation;
use App\Models\Product\Atlas;
use App\Services\QiniuServices;
use Illuminate\Support\Facades\DB;



class FabricController extends AdminController
{
    /**
     * 列表
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
         return View::make('admin.product.index');
    }

    /**
     * 数据接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {

        $created_at = $request->get('created_at') ?? null;
        $lang = $request->get('lang', 'zh');
        $keyword = $request->get('title');

        $model = ProductTranslation::query();
        if ($lang) {
            $model = $model->where('locale', $lang);
        }

        if (!empty($keyword)) {
            $model = $model->where('title', 'like', "%{$keyword}%")->orWhere('description', 'like', "%{$keyword}%")->orWhere('body','like', "%{$keyword}%");
        }

        if (!empty($created_at)) {
            $startime = substr($created_at, 0, 20);
            $endtime = substr($created_at, -20, 20);
            $model = $model->whereBetween('created_at', [$startime, $endtime]);
        }
        $res = $model->with('column')->condition()->orderBy('id', 'desc')->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items(),
        ];
        return Response::json($data);
    }

    public function create()
    {
       
        //分类
        $GoodsType = $this->getColumnClass('Product');
        return View::make('admin.product.create', compact('GoodsType'));
    }

    /**
     * 添加
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $data = $request->except(['_token', 'file']);
		$request = (object)$data;
        DB::beginTransaction();
       // try {
            $Product = new MainProduct();
            $Product->name = $request->title;
            $Product->column_id = $request->column_id;
            $Product->online = 1;

            foreach (config('translatable.locales') as $locale => $item) {
				$Product = $this->createItem($Product,$request,$locale);
            }
            if($Product->save()){
                DB::commit();
                return Response::json(['code' => 0, 'msg' => '添加成功', 'data' => '添加成功']);
            }

       // } catch (\Exception $exception) {
            DB::rollback();
       // }
        return Response::json(['code' => 0, 'msg' => '添加失败', 'data' => '添加失败']);
    }


    /**
     * 更新
     * @param $id
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(Request $request)
    {
        $id = (int)$request->get('id');
        $locale = $request->get('locale');
        $Product = MainProduct::whereTranslation('id', $id)->firstOrFail();
        $Product = $Product->translate($locale);
        //分类
        $GoodsType = $this->getColumnClass('Product');

        return View::make('admin.product.edit', compact('Product', 'GoodsType', 'locale'));
    }

    /**
     * 更新
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request)
    {
        $id = (int)$request->get('id');
  
        $Product = ProductTranslation::where('id', $id)->firstOrFail();
        $MainProduct = MainProduct::where('mid',$Product->product_mid)->firstOrFail();
        $data = $request->except(['file', '_token']);
		$request = (object)$data;
        DB::beginTransaction();
        $Product->column_id = $request->column_id;
        try {

            //从表 栏目ID同步更新
            foreach (config('translatable.locales') as $locale => $item) {
				if(!$MainProduct->hasTranslation($locale)){
					$MainProduct = $this->createItem($MainProduct,$request,$locale);
				}
				$MainProduct->translateOrNew($locale)->column_id = $request->column_id;
            }
            $MainProduct->save();
			$Product->update($data);
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '更新成功', 'data' => '更新成功']);
        } catch (\Exception $exception) {
            DB::rollback();
        }
        return Response::json(['code' => 0, 'msg' => '更新失败', 'data' => '更新失败']);
    }

   //更新状态
    public function updateAjax(Request $request)
    {
        $id = (int)$request->get('id');
        $Product = ProductTranslation::where('id', $id)->first();
        $data = $request->all();
        DB::beginTransaction();
        try {
            $Product->update($data);
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '状态更新成功', 'data' => '状态更新成功']);
        } catch (\Exception $exception) {
            DB::rollback();

        }
        return Response::json(['code' => 1, 'msg' => '状态更新失败', 'data' => $exception->getMessage()]);
    }


    public function destroy(Request $request,QiniuServices $qiniu)
    {
        $ids = (array)$request->get('ids');
        if (!is_array($ids) || empty($ids)) {
            return Response::json(['code' => 1, 'msg' => '请选择删除项']);
        }
        DB::beginTransaction();
        try {
            foreach ($ids as $id){

				$Product = ProductTranslation::where('id', $id)->first();
				$mainProduct = MainProduct::where('mid', $Product->product_mid)->firstOrFail();
				
				foreach($mainProduct->translations as $item){
					//删除产品资源
					$qiniu->objFromDelete($item);
					//删除图集
					$Atlas = Atlas::where('product_id',$item->id)->get();
					$qiniu->batchDelete($Atlas);
					//删除记录
					Atlas::where('product_id',$item->id)->delete();
				}
				$mainProduct->deleteTranslations();
            }
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $exception) {
            DB::rollback();
            
        }
		return Response::json(['code' => 1, 'msg' => '删除失败', 'data' => $exception->getMessage()]);
    }
	
	
	private function createItem($Product,$request,$locale){
		
                $Product->translateOrNew($locale)->column_id = $request->column_id;
                $Product->translateOrNew($locale)->title = $request->title."_".$locale;
                $Product->translateOrNew($locale)->seo_title = $request->seo_title;		
                $Product->translateOrNew($locale)->keywords = $request->keywords;
                $Product->translateOrNew($locale)->description = $request->description;
                $Product->translateOrNew($locale)->thumb = $request->thumb;
                $Product->translateOrNew($locale)->body = $request->body;
                $Product->translateOrNew($locale)->updated_at = now();
                $Product->translateOrNew($locale)->created_at = now();
			return $Product;
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
